<?php

namespace App\Http\Controllers\Backend;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Validator;
//use DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Post;
use Auth;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
//        $articles = Post::all();
//        $articles = DB::table('posts')->paginate(8);
        $articles = Post::with('hasOneUser')->latest()->paginate(8);
        return view('backend.posts.show', compact('articles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return view('backend.posts.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        /* 使用该方法, 如果验证失败, 直接携带错误信息跳转回原页面
        $this->validate($request, [
            'post_title' => 'required',
            'post_content' => 'required'
        ]);
        */
        $validator = Validator::make($request->all(), [
            'post_title' => 'required',
            'post_content' => 'required'
        ]);
        if ($validator->fails()) {
            alert()->error('验证失败', $validator->messages()->first());
//            alert()->overlay('验证失败', $validator->messages()->first(), 'error');
            return redirect()->back();
        }
        $array = $request->all();
        if (!isset($array['published_at'])) $array['published_at'] = Carbon::now();
        $user = Auth::user();
        $post = new Post($array);
        $post->post_author = $user->id;
        $post->save();
        return redirect(route('backend.posts.index'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $article = Post::find($id);

        return $article;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}
